import { prisma } from '../../utils/prisma'
import { getUserIdOrThrow } from '../../utils/guard'

export default eventHandler(async (event) => {
  getUserIdOrThrow(event)
  const id = Number(getRouterParam(event, 'id'))
  if (!Number.isFinite(id)) throw createError({ statusCode: 400, statusMessage: 'BAD_ID' })
  const rec = await prisma.activityRecord.findUnique({ where: { id } })
  if (!rec) throw createError({ statusCode: 404, statusMessage: 'NOT_FOUND' })

  await prisma.$transaction(async (tx) => {
    // 删除流水记录（从总分中扣除）
    await tx.pointsLedger.deleteMany({
      where: {
        sourceType: 'activity',
        sourceId: id
      }
    })

    // 将活动记录的积分设为0（标记为已删除，但保留记录）
    await tx.activityRecord.update({
      where: { id },
      data: { points: 0, note: rec.note ? `${rec.note} [已删除]` : '[已删除]' }
    })
  })

  return { ok: true }
})


